import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select,Tooltip,Divider} from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { listIngredient,del,add,edit,getIngredientInfoById,delReport,delScreen,addReport,editReport,addScreen,editScreen,importReport} from "@/api/modules/literdata";
import { list} from "@/api/modules/inci";
import { upload } from "@/api/modules/common";
import { ProFormColumnsType } from '@ant-design/pro-components'
import FullscreenLoading from '@/components/FullscreenLoading';
import { getInfo } from "@/api/login/ssoLogin";

const { Option } = Select;
const literData = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [onReloadNum, setReloadNum] = useState(null); 
  const [isModalVisibleUpload, setIsModalVisibleUpload] = useState(false);  
  const [selectedType, setSelectedType] = useState('3'); 
  const [loading, setLoading] = useState(false); // 加载状态 
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 


  // 使用useEffect在组件挂载时获取数据  
  useEffect(() => {  
    getInfo().then(res=>{
      console.log(res,'res')
      let data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 

  }, []);

  const formColumns:ProFormColumnsType[] = [{
    title: t('Ingredient'),
    dataIndex: 'search',
    valueType: 'text', 
  } ]

  const columns: any = [
    {
      title: t('Ingredient'),
      dataIndex: 'ingredient',
      key: 'ingredient',
      width: 100,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (ingredient) => (
        <Tooltip placement="topLeft" title={ingredient}>
          {ingredient}
        </Tooltip>
      ),
    },
    {
      title: t('ing.lawInciSerial'),
      dataIndex: 'lawInciSerial',
      width: 100,
      key: 'lawInciSerial',
      ellipsis: {
        showTitle: false,
      },
      render: (lawInciSerial) => (
        <Tooltip placement="topLeft" title={lawInciSerial}>
          {lawInciSerial}
        </Tooltip>
      ),
    },
    {
      title: t('ing.inciUs'),
      dataIndex: ['inci','inciEu'],
      width: 120,
      key: 'inci.inciEu',
      ellipsis: {
        showTitle: false,
      },
      render: (inciEu) => (
        <Tooltip placement="topLeft" title={inciEu}>
          {inciEu}
        </Tooltip>
      ),
    },
    {
      title: t('ing.inciCn'),
      dataIndex: ['inci','inciCn'],
      width: 120,
      key: 'inci.inciCn',
      ellipsis: {
        showTitle: false,
      },
      render: (inciCn) => (
        <Tooltip placement="topLeft" title={inciCn}>
          {inciCn}
        </Tooltip>
      ),
    },
    {
      title: t('ing.finding'),
      dataIndex: 'finding',
      key: 'finding',
      width:80,
      ellipsis: {
        showTitle: false,
      },
      render: (finding) => (
        <Tooltip placement="topLeft" title={finding}>
          {finding}
        </Tooltip>
      ),
    },
    {
      title: t('ing.description'),
      dataIndex: 'description',
      key: 'description',
      width:80,
      ellipsis: {
        showTitle: false,
      },
      render: (description) => (
        <Tooltip placement="topLeft" title={description}>
          {description}
        </Tooltip>
      ),
    },
    {
      title: t('ing.conclusion'),
      dataIndex: 'conclusion',
      key: 'conclusion',
      width:200,
      ellipsis: {
        showTitle: false,
      },
      render: (conclusion) => (
        <Tooltip placement="topLeft" title={conclusion}>
          {conclusion}
        </Tooltip>
      ),
    },
    {
      title: t('ing.conclusionCn'),
      dataIndex: 'conclusionCn',
      key: 'conclusionCn',
      ellipsis: {
        showTitle: false,
      },
      render: (conclusionCn) => (
        <Tooltip placement="topLeft" title={conclusionCn}>
          {conclusionCn}
        </Tooltip>
      ),
    },
    {
      title: t('ing.source'),
      dataIndex: 'source',
      key: 'source',
      width:80,
      ellipsis: {
        showTitle: false,
      },
      render: (source) => (
        <Tooltip placement="topLeft" title={source}>
          {source}
        </Tooltip>
      ),
    },
    {
      title: t('ing.remark'),
      dataIndex: 'remark',
      key: 'remark',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (remark) => (
        <Tooltip placement="topLeft" title={remark}>
          {remark}
        </Tooltip>
      ),
    },
    {
      title: t('ing.max3yearLeaveon'),
      dataIndex: 'max3yearLeaveon',
      key: 'max3yearLeaveon',
      ellipsis: {
        showTitle: false,
      },
      render: (max3yearLeaveon) => (
        <Tooltip placement="topLeft" title={max3yearLeaveon}>
          {max3yearLeaveon}
        </Tooltip>
      ),
    },  
    {
      title: t('ing.max3yearRinseoff'),
      dataIndex: 'max3yearRinseoff',
      key: 'max3yearRinseoff',
      ellipsis: {
        showTitle: false,
      },
      render: (max3yearRinseoff) => (
        <Tooltip placement="topLeft" title={max3yearRinseoff}>
          {max3yearRinseoff}
        </Tooltip>
      ),
    },  
    {
      title: t('ing.safetyConclusion'),
      dataIndex: 'safetyConclusion',
      key: 'safetyConclusion',
      ellipsis: {
        showTitle: false,
      },
      render: (safetyConclusion) => (
        <Tooltip placement="topLeft" title={safetyConclusion}>
          {safetyConclusion}
        </Tooltip>
      ),
    },  
    {
      title: t('ing.citation'),
      dataIndex: 'citation',
      key: 'citation',
      ellipsis: {
        showTitle: false,
      },
      render: (citation) => (
        <Tooltip placement="topLeft" title={citation}>
          {citation}
        </Tooltip>
      ),
    },  
    {
      title: t('ing.OriginalFile'),
      dataIndex: 'OriginalFile',
      key: 'OriginalFile',
      width:150,
      render: (text, record) => { // text是dataIndex对应的值（这里可能不需要），record是当前行的数据  
        return (  
          <div style={{ display: 'grid' }}>  
            {record.reports.map((item, index) => (  
              <Tooltip  
                key={index}  
                title={  
                  <div>  
                    决策： {item.decisionRead}  
                    <br />  
                    Reference：{item.dateReference || ''}  
                  </div>  
                }  
                placement="topLeft"  
              >  
                <a  
                  href={`/res-dir/Articel/Original/${item.filename}`} // 注意这里你可能需要使用其他方式处理链接，比如使用router  
                  target="_blank" // 如果需要在新标签页打开  
                  style={{ color: 'green'}}  
                >  
                  {item.filename}  
                </a>  
              </Tooltip>  
            ))}  
          </div>  
        );  
      },  
    },  
    // {
    //   title: t('ing.QuickCheckPage'),
    //   dataIndex: 'QuickCheckPage',
    //   key: 'QuickCheckPage',
    //   width:150,
    //   render: (text, record) => { // text是dataIndex对应的值（这里可能不需要），record是当前行的数据  
    //     return (  
    //       <div style={{ display: 'grid' }}>  
    //         {record.reportScreens.map((item, index) => (  
    //             <a  
    //               href={`/res-dir/Articel/Screen/${item.filename}`} // 注意这里你可能需要使用其他方式处理链接，比如使用router  
    //               target="_blank" // 如果需要在新标签页打开  
    //               style={{ color: 'green' }}  
    //             >  
    //               {item.filename}  
    //             </a>  
    //         ))}  
    //       </div>  
    //     );  
    //   },  
    // },  
    {
      title: t('ing.updateBy'),
      dataIndex: 'updateBy',
      key: 'updateBy',
      width:130,
    },  
    {
      title: t('ing.colour'),
      dataIndex: 'colour',
      key: 'colour',
      width:130,
    },  
    {
      title: t('ing.updateOn'),
      dataIndex: 'updateOn',
      key: 'updateOn',
      width:130,
    },  
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
          {viewStatus ? null : (
            <>
              <Button type="link" onClick={() => handleEdit(record)}>  
              {t('edit')}  
              </Button>  
            </>
          )}
          {/* <Button type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>   */}
   
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await listIngredient({...formData, orderby: 'a.update_on', order: 0})
    if(!success) return false
    console.log(data)
    const list2 = data.data.page
    return {
      data: list2,
      total: data.data.total
    }
  } 


  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    if(Title=='新增/New'){
        //新增
        values.id =null
        add(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        edit(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleAdd = () =>{
    // 跳转到'/sa/addreport'路径，并带上id参数  
    navigate(`/safety/literdataDetail?view=0`); 
  }

  const handleView = (record) =>{
    navigate(`/safety/literdataDetail?id=`+record.id +'&view=1');
  }

  const handleEdit = (record) =>{
    navigate(`/safety/literdataDetail?id=`+record.id +'&view=0');
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        del(inciIds).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const showModal2 = () => {  
    setIsModalVisibleUpload(true);  
  };  
  
  const handleFileChange = (info) => { 
    console.log(info,'info')
    info.file.status = "done"
    if(info.fileList.length==0){

    }else{
      setLoading(true);
      const files = info.fileList[0].originFileObj
        let formData = new FormData();
        formData.append("file", files);
        formData.append("test_id",selectedType);
        importReport(formData).then(response=>{
          if (response.data.status == 0) {
              message.success("Success")
              setIsModalVisibleUpload(false)
              setLoading(false);
          }else{
         let message1 = ""
         message1 += response.data.message+'<br/>'
         response.data.data.map(i=>{
            message1 += i+' <br/>'
         })
         message.error(message1)
         setLoading(false);
         setIsModalVisibleUpload(false)
          }
          }).catch(()=>{
            setLoading(false);
            setIsModalVisibleUpload(false)
          })
    }
  };  

  const handleDownload = () => {  
    // 这里可以添加处理下载操作的逻辑，比如调用下载接口  
    download("/api/exportCirTemplate", {
      
    }, `Zan Ya Template_ingredient.xlsx`);
  };  
  
  const handleCancel2 = () => {  
    setIsModalVisibleUpload(false);  
  }; 

  const handleTypeChange = (value) => {  
    setSelectedType(value);  
  };  

  const renderOperator = <>
    <Button disabled={viewStatus} type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
    <Button disabled={viewStatus} style={{marginLeft:'1%'}} size="small" type="primary" onClick={showModal2}>  
          {t('IngredientImport')}  
        </Button> 
  </>
  
  return (
    <div> 
       <FullscreenLoading showLoading={loading} loadingTip="Loading..."/>  
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
        title="Subject Data Import"  
        visible={isModalVisibleUpload}  
        onCancel={handleCancel2} 
        destroyOnClose 
        footer={null} // 隐藏默认的footer  
      >  
        <div style={{ marginBottom: '16px' }}>  
          <Button type="primary" onClick={handleDownload}>  
            {t('report.templateDownload')}  
          </Button>  
        </div>  
        <p style={{ color: 'red', fontSize: '12px' }}>*{t('IngredientUpload2')}</p>  
        <div style={{ marginBottom: '16px' }}> 
        <span style={{color:'red',fontSize:'12px'}}>*</span><span style={{fontSize:'12px'}}>类型</span>
          <Select  
            defaultValue="3"  
            style={{ width: 120, marginLeft: '10px' }}  
            value={selectedType}  
            onChange={handleTypeChange}  
          >  
            <Option value="3">通用</Option>  
            <Option value="11">儿童</Option>  
          </Select>  
        </div>  
        <Divider style={{ marginBottom: '16px' }} />  
        <Upload  
                customRequest={({ file, onSuccess, onError }) => {  
                  // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                  // 例如，使用axios发送POST请求上传文件  
                  // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                onChange={handleFileChange} 
              >  
                <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
              </Upload> 
      </Modal> 
    </div>
  )
}
export default literData
